package com.example.smsend;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.activity.CaptureActivity;
import com.google.zxing.util.Constant;
import com.google.zxing.util.QrCodeGenerator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    public static final int REQUEST_CODE_SCAN = 0X02;
    private static final int COMPLETED = 0;
    public static String SmsList;
    private ListView listview1;
    SimpleAdapter sa;
    String key;  // 本地秘钥
    List<Map<String,Object>> list;// 短信内容
    TextView lastTime;

    String values;

    ImageButton btnQrCode; // 扫码
    TextView tvResult; // 结果
    ImageView imgQrcode; // 二维码图片

    Integer DevicesStatus = 0; // 当前设备
    Integer readStatus = 1; //读取状态 1未读 2在读

    public static String deviceId;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvResult = (TextView) findViewById(R.id.nowDevice);
        btnQrCode = (ImageButton) findViewById(R.id.btn);
        btnQrCode.setOnClickListener(this);

        Button lookSmsBtn = (Button) findViewById(R.id.lookSms);
        lookSmsBtn.setOnClickListener(this);
        lastTime = findViewById(R.id.lastTime);


        imgQrcode = (ImageView) findViewById(R.id.img_qrcode);

        //获取设备ID
        deviceId =  Settings.Secure.getString(getBaseContext().getContentResolver(), Settings.Secure.ANDROID_ID);


        //获取多项权限
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.RECEIVE_SMS,
                Manifest.permission.READ_SMS
        },1);

        //秘钥读写
        String path = String.valueOf(this.getFilesDir())+"/key";
        File file = new File(path);

        try{
            FileInputStream fin = new FileInputStream(file);
            byte[] ramdom = new byte[fin.available()];
            fin.read(ramdom);
            key = new String(ramdom);
            fin.close();
        } catch(Exception e){
            e.printStackTrace();
        }

        try{
            if(key == null){
                FileOutputStream fout = new FileOutputStream(file);
                key = String.valueOf(getRamdom(10));
                fout.write(key.getBytes());
                fout.close();
            }
        } catch(Exception e){
            e.printStackTrace();
        }


        //二维码生成
        new Handler().postDelayed(()->{
            generateQrCode();
        },100);

        // 绑定状态
        getBindStatus();

        // 轮训推送最新短信 20秒一次
        lun();
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn:
                //扫码功能
                ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeCustomAnimation(this, 1, 2);
                Intent intent = new Intent(this, CaptureActivity.class);
                ActivityCompat.startActivityForResult(this, intent, REQUEST_CODE_SCAN, optionsCompat.toBundle());

                break;
            case R.id.lookSms:
                lookSms();
                break;
            default:
                break;
        }

    }

    private void pushSms()
    {
        Cursor cursor=getContentResolver().query(Uri.parse("content://sms/inbox"),
                null,null,null,null);

        cursor.moveToNext();
        int smsbodyColumn = cursor.getColumnIndex("body");// 短信内容
        String smsbody = cursor.getString(smsbodyColumn);

        //短信内容RC4加密
        smsbody = HloveyRC4(smsbody,key);

        values = "smsbody="+smsbody;

        new Thread() {
            @Override
            public void run() {
                Http request = new Http();
                String res = request.post("服务端地址", values,deviceId);//调用我们写的post方法
                if(!Objects.equals(res, "-1")){
                    JSONObject res1 = JSONObject.parseObject(res);
                    if("-1".equals(String.valueOf(res1.get("code")))){
                        Message msg =  new Message();
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }
                    if("1".equals(String.valueOf(res1.get("code")))){
                        Message msg =  new Message();
                        msg.what = 3;
                        msg.obj = String.valueOf(res1.get("time"));
                        Log.v("time",String.valueOf(res1.get("time")));
                        handler.sendMessage(msg);
                    }
                }
            }
        }.start();
    }

    public void getBindStatus()
    {
        new Thread() {
            @Override
            public void run() {
                Http request = new Http();
                String res = request.post("服务端地址", "" ,deviceId);

                if("-1".equals(res)){
                    Message msg =  new Message();
                    msg.what = 2;
                    handler.sendMessage(msg);
                }else{
                    JSONObject res1 = JSONObject.parseObject(res);
                    if("1".equals(String.valueOf(res1.get("code")))){
                        Message msg =  new Message();
                        msg.what = COMPLETED;
                        handler.sendMessage(msg);

                        DevicesStatus = (int) res1.get("devStatus");

                                //控端识别
                        Message msg1 =  new Message();
                        msg1.what = (int) res1.get("devStatus");
                        handler.sendMessage(msg1);

                    }
                }

            }
        }.start();

    }

    private void lookSms() {
        if(readStatus == 1){
//            readStatus = 2;
            new Thread() {
                @Override
                public void run() {
                    Http request = new Http();
                    String res = request.post("服务端地址", "",deviceId);//调用我们写的post方法

                    if(!Objects.equals(res, "-1")){
                        JSONObject res1 = JSONObject.parseObject(res);
                        if("-1".equals(String.valueOf(res1.get("code")))){
                            Message msg =  new Message();
                            msg.what = 2;
                            handler.sendMessage(msg);
                        }
                        if("1".equals(String.valueOf(res1.get("code")))){
                            JSONArray list2 = JSONArray.parseArray(String.valueOf(res1.get("data")));
                            list = (List<Map<String, Object>>) translate(list2);


                            Message msg =  new Message();
                            msg.what = 4;
                            msg.obj = String.valueOf(res1.get("time"));

                            handler.sendMessage(msg);

                        }
                    }
                    readStatus = 1;
                }
            }.start();
        }
    }



    public static Object translate(JSONArray json) {
        List<Object> list = new ArrayList<Object>();
        for (Object o : json) {
            if (o instanceof JSONArray)
                list.add(translate((JSONArray) o));
            else
                list.add(o);
        }
        return list;
    }


    public void showSms()
    {
        if(list == null){
            Toast.makeText(getApplicationContext(), "暂无短信可展示", Toast.LENGTH_SHORT).show();
            return;
        }

        for(Map<String,Object> StringOjbectMap : list){
            String smsbody1 = (String) StringOjbectMap.get("smsbody");

//            StringOjbectMap.put("smsbody1",smsbody1);

            StringOjbectMap.put("smsbody1",HloveyRC4(smsbody1,key));
        }

        listview1=findViewById(R.id.listview);
        sa = new SimpleAdapter(getApplicationContext(),list, R.layout.activity_item,new String[]{"phone","smsbody1","date1"},new int[]{R.id.phone,R.id.smsbody,R.id.date});
        listview1.setAdapter(sa);


        ListAdapter listAdapter = listview1.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;

        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int widthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST);

        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listview1);


            listItem.measure(widthSpec, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listview1.getLayoutParams();
        params.height = totalHeight
                + (listview1.getDividerHeight() * (list.size() -1 ));
        listview1.setLayoutParams(params);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);

            //将扫描出的信息显示出来
//            tvResult.setText(scanResult);

            Handler mainHandler = new Handler(Looper.getMainLooper()){

            };//更新UI主线程

            String[] result = scanResult.split("&key=");

            scanResult = result[0];
            String finalScanResult = scanResult;

            key = result[1];

            //识别后将接收端的加密存储在本地
            String path = String.valueOf(this.getFilesDir())+"/key";
            File file = new File(path);
            try{
                FileOutputStream fout = new FileOutputStream(file);
                fout.write(key.getBytes());
                fout.close();
            } catch(Exception e){
                e.printStackTrace();
            }

            new Thread() {
                @Override
                public void run() {
                    Http request = new Http();
                    String data = "getDev="+ finalScanResult +"&setDev="+deviceId;//POST请求的参数

                    String res = request.post("服务端地址", data ,deviceId);//调用我们写的post方法
                    JSONObject res1 = JSONObject.parseObject(res);
                    if("1".equals(String.valueOf(res1.get("code")))){
                        Message msg =  new Message();
                        msg.what = COMPLETED;
                        handler.sendMessage(msg);
                    }
                }
            }.start();

        }
    }

    @SuppressLint("HandlerLeak")
    private Handler handler =  new Handler()
    {
        @Override
        public  void handleMessage(Message msg)
        {
            if (msg.what == COMPLETED)
            {
                tvResult.setText( "已绑定");
                tvResult.setTextColor(Color.parseColor("#3ddc84"));
            }

            if(2 == msg.what){
                Toast.makeText(getApplicationContext(), "请扫码绑定设备", Toast.LENGTH_SHORT).show();
            }
            if(3 == msg.what){
                lastTime.setText(new String((String) msg.obj));
            }
            if(66666 == msg.what){
                pushSms();
            }
            if( 88888 == msg.what){
                LinearLayout title = findViewById(R.id.title);
                title.setVisibility(View.GONE);
                showSms();
            }
            if(-1 == msg.what){
                Toast.makeText(getApplicationContext(), "请求失败", Toast.LENGTH_SHORT).show();
            }

            if(4 == msg.what){
                showSms();
                lastTime.setText(new String((String) msg.obj));

            }
        }
    };

    /**
     * 生成二维码
     */
    private void generateQrCode() {
        if (deviceId.equals("")) {
            Toast.makeText(this, "请输入二维码内容", Toast.LENGTH_SHORT).show();
            return;
        }

        Bitmap bitmap = QrCodeGenerator.getQrCodeImage(deviceId+"&key="+key, imgQrcode.getWidth(), imgQrcode.getHeight());
        if (bitmap == null) {
            Toast.makeText(this, "生成二维码出错", Toast.LENGTH_SHORT).show();
            imgQrcode.setImageBitmap(null);
        } else {
            imgQrcode.setImageBitmap(bitmap);
        }
    }


    public StringBuffer getRamdom(int a)
    {
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random1=new Random();
        //指定字符串长度，拼接字符并toString
        StringBuffer sb=new StringBuffer();
        for (int i = 0; i < a; i++) {
            //获取指定长度的字符串中任意一个字符的索引值
             int number=random1.nextInt(str.length());
            //根据索引值获取对应的字符
             char charAt = str.charAt(number);
            sb.append(charAt);
        }
        return sb;
    }


    public void lun()
    {
        new Thread(){
            @Override
            public void run()
            {
                try {
                    Thread.sleep(20000);
                    if(DevicesStatus == 66666){
                        pushSms();
                        lun();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    public static String HloveyRC4(String aInput,String aKey)
    {
        int[] iS = new int[256];
        byte[] iK = new byte[256];
        for (int i=0;i<256;i++)
            iS[i]=i;
        int j = 1;
        for (short i= 0;i<256;i++)
        {
            iK[i]=(byte)aKey.charAt((i % aKey.length()));
        }
        j=0;
        for (int i=0;i<255;i++)
        {
            j=(j+iS[i]+iK[i]) % 256;
            int temp = iS[i];
            iS[i]=iS[j];
            iS[j]=temp;
        }
        int i=0;
        j=0;
        char[] iInputChar = aInput.toCharArray();
        char[] iOutputChar = new char[iInputChar.length];
        for(short x = 0;x<iInputChar.length;x++)
        {
            i = (i+1) % 256;
            j = (j+iS[i]) % 256;
            int temp = iS[i];
            iS[i]=iS[j];
            iS[j]=temp;
            int t = (iS[i]+(iS[j] % 256)) % 256;
            int iY = iS[t];
            char iCY = (char)iY;
            iOutputChar[x] =(char)( iInputChar[x] ^ iCY) ;
        }
        return new String(iOutputChar);
    }


}